package com.hd.config;

import com.hd.realm.UserRealm;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro的核心配置文件类
 * @author 59899
 * @Configuration 配置文件类
 */
@Configuration
public class ShiroConfig {

    @Bean("ehCacheManager")
    public EhCacheManager getEhCacheManager() {
        return new EhCacheManager();
    }

    /**
     * 1.自定义realm
     * @Bean("userRealm") <bean id="userRealm" class="com.lzp.realm.UserRealm"/>
     */
    @Bean("userRealm")
    public UserRealm getUserRealm() {
        return new UserRealm();
    }

    /**
     *  2.创建securityManager对象
     *  在方法的参数中定义对象 该对象就会自动的从ioc容器中获取并赋值
     *  如果名称和ioc容器中的名称不一致 则可以使用@Qualifier指明
     */
    @Bean("securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("userRealm") UserRealm userRealm,
                                                        @Qualifier("ehCacheManager") EhCacheManager ehCacheManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        securityManager.setCacheManager(ehCacheManager);
        return securityManager;
    }

    /**
     * 3.创建前端过滤器对象
     */
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);
        //设置请求和页面的过滤规则  anon authc user 使用有序的map集合
        Map<String, String> map = new LinkedHashMap<>();
        map.put("/login","anon");
        map.put("/img/*","anon");
        bean.setFilterChainDefinitionMap(map);
        //设置没有认证跳转的页面
        bean.setLoginUrl("/toLogin");
        //设置没有权限跳转的页面 [该功能失效 使用springboot处理该异常]
        bean.setUnauthorizedUrl("/toLogin");
        return bean;
    }

}
